import React from 'react';
import Item from '../testItem';
import HOST from '../../../../utils/const'
import axios from 'axios';
import { useState } from 'react';
import './index.css';

function Problem(props) {
    const [finish, setFinish] = useState(false);
    const [score, setScore] = useState(null);
    const answers = []
    const getAnswer = (item, index) => {
        answers[index] = item;
    }
    const getScore = () => {
        const usn = localStorage.getItem('username');
        axios.get(HOST + `/method/answer?username=${usn}&answer=${answers.join('')}`).then((res) => {
            switch (res.data.split('\n')[0]) {
                case 'code=7': {
                    setScore(res.data.split('\n')[2])
                    break;
                }
                default: {
                    alert('未知错误');
                    break;
                }
            }
        }).catch((err) => {
            console.log(err);
        })
    }
    return (
        <div className='test'>
            <div className='left-test'>
                <div className='test-left-item'>测试</div>
            </div>
            <div className='right-test-zone'>
                <div className='test-zone'>
                    {props.detail ? props.detail.map((item, index) =>
                        <Item question={item.question} answer={item.answer} index={index} key={item.question+Math.random()*100} getAnswer={getAnswer} />
                    ) : null}
                </div>
                <div className='check-test-button'  style={finish ? { display: 'none' } : { display: "block" }} onClick={() => {

                    if (answers.join('').length < props.detail.length) {
                        alert('请全部作答完成');
                        return;
                    }
                    getScore();
                    setFinish(true);
                }}>作答结束</div>
                <div className='test-score' style={score ? { display: 'block' } : { display: "none" }}>本次作答共获得{score ? Math.round(score)  : null}分</div>
            </div>
        </div>


    );
}


export default Problem;
